package mygang.controller.manager;

import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import mygang.controller.AbstractController;
import mygang.helper.ControllerHelper;
import mygang.model.SystemSetting;
import mygang.service.manager.SettingService;
import mygang.singleton.Settings;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 *
 * @author Volodymyr Lavrynovych <volodya.lavrynovych@gmail.com>
 * date: 25/02/2013
 */
@Controller
@RequestMapping(AbstractController.MANAGE_SETTING)
public class SettingController extends AbstractManageController<SettingService, SystemSetting> {

    private static final Logger log = Logger.getLogger(SettingController.class.toString());

    SystemSetting prepareObject(HttpServletRequest request) throws Exception {
        String tempId = request.getParameter("id");
        Long id = tempId!=null && !tempId.isEmpty() ? new Long(request.getParameter("id")) : null;
        
        String name = request.getParameter("name");
        if(name==null || name.isEmpty()) throw new Exception("Name is not specified");
        String value = request.getParameter("value");
        String desc = request.getParameter("desc");
        
        return id==null ? new SystemSetting(name, value, desc) : new SystemSetting(id.longValue(), name, value, desc);
    }

    String getLink() {
        return MANAGE_SETTING;
    }
    
    /**
     * Refreshes App System Settings
     * @param response contains response for client-side
     * @throws IOException 
     */
    @RequestMapping(value = "/refresh", method = RequestMethod.POST)
    public void refresh(HttpServletResponse response) throws IOException {
        try {
            Settings.getInstance().refresh();;
            ControllerHelper.success(response);
        } catch (Exception ex) {
            ControllerHelper.handleException(ex, response);
        }
    }
}